/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Server;

import java.sql.*;

/**
 * The Database class is responsible for
 * all the interactions with the Database
 * like adding a user, checking a usernames
 * availability.
 * @author sajin
 */
public class Database {

	/**
	 * The MySQL Database connection details are
	 * passed on to this constructor.
	 * @param userName userName for the database user.
	 * @param passWord passWord for the database user.
	 * @param serverUrl URL of the database.
	 */
	public Database(String userName,String passWord,String serverUrl) throws ClassNotFoundException,IllegalAccessException,InstantiationException{
		this.userName = userName;
		this.passWord = passWord;
		this.serverUrl = serverUrl;
		dbConnection = null;
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		try {
			dbConnection = DriverManager.getConnection(serverUrl, userName, passWord);
			Statement createUserTable = dbConnection.createStatement();
			createUserTable.executeUpdate(
				"CREATE TABLE IF NOT EXISTS users("+
				"UserName varchar(40) NOT NULL," +
				"PassWord varchar(128) NOT NULL," +
				"PublicKey varchar(512) NOT NULL," +
				"PRIMARY KEY(UserName))"
				);
		} catch (SQLException sqExp) {
			System.out.println("Error Occured " + sqExp.getLocalizedMessage());
		}
	}

	@Override
	protected void finalize() throws Throwable {
		dbConnection.close();
	}

	/**
	 * Check with the database that the
	 * user name is already taken or not.
	 * @return True if user name is available.
	 *	   False otherwise.
	 */
	public boolean checkAvailUserName( String userName ) {
		int userCount = 0;
		
		try {
			Statement userAvail = dbConnection.createStatement();
			userAvail.execute(
				"SELECT COUNT(*) FROM users WHERE UserName='" +
				userName + "'"
				);
			ResultSet resultUserAvail = userAvail.getResultSet();
			resultUserAvail.first();
			userCount = resultUserAvail.getInt(1);
			userAvail.close();
		} catch ( SQLException sqlExp ) {
			System.err.println("Error Occured " + sqlExp.getMessage() );
		}
		
		if ( userCount == 1 )
			return false;
		else
			return true;
	}

	/**
	 * Adds a user to the users table stored in the database.
	 * @param userName
	 * @param passWord
	 * @param publicKey
	 * @return True if the username is available and the user is
	 *         added to the database.
	 *	   False if the user name is already taken.
	 */
	public boolean AddUser(String userName,String passWord,String publicKey) {
		if ( checkAvailUserName(userName) )
		{
			try {
				Statement addUser = dbConnection.createStatement();
				addUser.execute(
					"INSERT INTO users values('" +
					userName + "'," +
					"'" + passWord + "'," +
					"'" + publicKey + "');"
					);
				addUser.close();
			} catch ( SQLException sqlExp ) {
				System.err.println( "Error Occured " + sqlExp.getMessage() );
			}

			return true;
		}
		else
			return false;
	}

	protected String userName;
	protected String passWord;
	protected String serverUrl;
	protected Connection dbConnection;
}
